/**
 * @author gao
 * @date 2025/7/1 16:12
 */

public class Demo2 {

    private static int count = 0;
    private static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 50_000; i++) {
                    count++;
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 50_000; i++) {
                    count++;
                }
            }
        });

        long beg = System.currentTimeMillis();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        long end = System.currentTimeMillis();

        System.out.println(count);

        System.out.println("耗时:" + (end - beg) + "ms");

        main1(args);
    }

    public static void main1(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50_000; i++) {
                // 进来就是加锁
                synchronized (lock) {
                    count++;
                }
                // 出去就是解锁
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50_000; i++) {
                // 第二个线程也加锁
                synchronized (lock) {
                    count++;
                }
            }
        });

        long beg = System.currentTimeMillis();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        long end = System.currentTimeMillis();

        System.out.println("耗时:" + (end - beg) + "ms");
    }
}